package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

public class MovieLibrary implements Library {
    private Map<String, Movie> availableList = new TreeMap<String, Movie>();
    private Map<String, Movie> checkedList = new TreeMap<String, Movie>();
    private BufferedReader reader;

    public MovieLibrary(BufferedReader reader) {
        this.reader = reader;
        initLibrary();
    }

    @Override
    public void initLibrary() {
        Movie movie1 = new Movie("name1", "year1", "director1", 2);
        Movie movie2 = new Movie("name2", "year2", "director2", 5);
        Movie movie3 = new Movie("name3", "year3", "director3", 8);
        availableList.put("1", movie1);
        availableList.put("2", movie2);
        availableList.put("3", movie3);
    }

    @Override
    public String display() {
        String result = "";
        Movie movie;
        for (String id : availableList.keySet()) {
            movie = availableList.get(id);
            result += id + "---" + movie.name + "---" + movie.year + "---" + movie.director + "---" + movie.rate + "\n";
        }
        System.out.println(result);
        return result;
    }

    public Map<String, Movie> availableMovie() {
        return availableList;
    }

    @Override
    public boolean checkout() throws IOException {
        System.out.println("Please input the movie id you want to check out: ");
        String id = reader.readLine();
        if (availableList.keySet().contains(id)) {
            checkedList.put(id, availableList.get(id));
            availableList.remove(id);
            System.out.println("Thank you! Enjoy the movie.\n");
            return true;
        }
        System.out.println("That movie is not available.\n");
        return false;
    }

    @Override
    public boolean returnItem() throws IOException {
        System.out.println("Please input the movie id you want to return: ");
        String id = reader.readLine();
        if (checkedList.containsKey(id)) {
            availableList.put(id, checkedList.get(id));
            checkedList.remove(id);
            System.out.println("Thank you for returning the movie.\n");
            return true;
        }
        System.out.println("That is not a valid movie to return.\n");
        return false;
    }

    public Map<String, Movie> checkedList() {
        return checkedList;
    }

}
